package com.songcha.module_task.ui.fragment.task

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.songcha.library_base.mvvm.base.BaseRefreshMvvmFragment
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.bean.banner.BannerBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.event.user.LogoutEvent
import com.songcha.library_business.handler.BookUriHandler
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_business.provider.IDailyTaskProvider
import com.songcha.library_business.proxy.configuration.SystemConfigurationManager
import com.songcha.library_business.proxy.database.BookTodayCommentWriteCountDaoManager
import com.songcha.library_business.proxy.database.BookTodayReadChapterCountDaoManager
import com.songcha.library_business.proxy.database.BookTodayReadTimeDaoManager
import com.songcha.library_business.proxy.database.TodayWatchRewardAdvertCountDaoManager
import com.songcha.library_business.proxy.login.IOnLoginSuccessEventListener
import com.songcha.library_business.proxy.login.LoginSuccessEvent
import com.songcha.library_business.proxy.main.MainEventProxy
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.dialog.CustomDialog
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.library_common.ui.view.CustomButton
import com.songcha.library_common.ui.view.CustomContainerLayout
import com.songcha.library_common.util.ColorUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.module_task.R
import com.songcha.module_task.bean.DailyTaskBean
import com.songcha.module_task.bean.SignTaskBean
import com.songcha.module_task.ui.adapter.DailyTaskAdapter
import com.songcha.module_task.ui.adapter.TaskBannerAdapter
import com.songcha.module_task.databinding.TaskFragmentTaskBinding
import com.songcha.module_task.event.DailyTaskCompleteEvent
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.bannerview.constants.PageStyle
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

@Route(path="/task/TaskFragment")
class TaskFragment : BaseRefreshMvvmFragment<TaskViewModel,TaskFragmentTaskBinding>(),OnItemChildClickListener,
    BottomNavigationView.IOnBottomNavigationItemChangeListener,IOnLoginSuccessEventListener,OnClickListener{

    private var mAdapter:DailyTaskAdapter?=null

    init {
        TAG=TaskFragment::class.java.simpleName
    }


    override fun getLayoutId(): Int {
        return R.layout.task_fragment_task
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

      /*  initSignView(mutableListOf())
        initBanner()
        initDailyTask(mutableListOf())*/

        //getData()
        databinding.taskLlGoldExplain.setOnClickListener (this)
        databinding.taskLlSignExplain.setOnClickListener (this)

        //initBannerAdvert()

    }

    private fun initBannerAdvert(){
        AdvertCoverHelper.loadAdvertByCover(requireActivity(),AdvertHelper.ADVERT_TYPE_BANNER,VarConfig.ADVERT_TASK_BANNER_INFO,
            databinding.taskFlAdvertBanner,0f,object:AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    ViewHelper.setVisibility(true,databinding.taskFlAdvertBanner)
                    if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                        databinding.taskFlAdvertBanner.removeAllViews()
                        databinding.taskFlAdvertBanner.addView(view)
                    }else if(type == AdvertInfoBean.ADVERT_TYPE_GDT){

                    }
                }

                override fun onError(type: Int, code: Int, msg: String) {
                    ViewHelper.setVisibility(false,databinding.taskFlAdvertBanner)
                    databinding.taskFlAdvertBanner.removeAllViews()
                }

                override fun onClose(type: Int) {
                    ViewHelper.setVisibility(false,databinding.taskFlAdvertBanner)
                    databinding.taskFlAdvertBanner.removeAllViews()
                }

            })
    }

    override fun initObserver() {
        viewModel.signTaskList.observe(this){data->
            if(viewModel.signDay.value!=null)
                initSignView(requireContext(),data,viewModel.signDay.value!!,databinding.taskLlSign)
        }

        viewModel.bannerList.observe(this){data->
            initBanner(data)
        }

        viewModel.signState.observe(this){data->
            if(data){
                val db=CustomDialog.Companion.Builder(requireContext())
                db.setDialogMsg("签到成功")
                    .setCancelText("")
                    .create()
                    .show()
                showTaskInfo()
            }
        }

        viewModel.signDay.observe(this){data->
            showTaskInfo()
        }

        viewModel.dailyTaskList.observe(this){data->
            initDailyTask(data)
        }

        viewModel.completeTaskState.observe(this){data->
            if(data){
                viewModel.getUserInfo()
                mAdapter?.notifyDataSetChanged()
            }
        }
    }

    override fun initListData() {

    }

    override fun getRefreshLayout(): SmartRefreshLayout {
       return databinding.taskSrl
    }

    override fun getListAdapter(): RecyclerView.Adapter<BaseViewHolder>? {
       return null
    }

    override fun onGetData() {
        viewModel.getUserInfo()
        viewModel.getSignTask()
        viewModel.getUserSignDay()
        viewModel.getTaskBanner()
        viewModel.getDailyTask()
    }

    override fun isNeedShowLoad(): Boolean {
        return true
    }

    override fun onResume() {
        super.onResume()
        showTaskInfo()
        mAdapter?.notifyDataSetChanged()
        initBannerAdvert()
    }

    private fun showTaskInfo(){
        if(UserInfoManager.checkLogin()){
            if(UserInfoManager.userInfo!!.signinPresentNumber>0){
                databinding.taskContinuteSignDay.text="已连续签到${viewModel.signDay.value!!}天"
            }else{
                databinding.taskContinuteSignDay.text="未签到"
            }
            databinding.taskTvMyGold.text="我的金币：${UserInfoManager.userInfo!!.gold}"
        }else{
            databinding.taskContinuteSignDay.text=""
        }
        //get sign day complete,then need to refresh sign list
        if(viewModel.signTaskList.value!=null)
            initSignView(requireContext(),viewModel.signTaskList.value!!,viewModel.signDay.value!!,databinding.taskLlSign)
    }


    private fun initBanner(list:MutableList<BannerBean.DataBean>){
        if(list.size==0){
            databinding.taskCclBanner.visibility=View.GONE
        }else{
            databinding.taskCclBanner.visibility=View.VISIBLE
            databinding.taskBvp.apply {
                adapter = TaskBannerAdapter() as BaseBannerAdapter<Any>
                setPageStyle(PageStyle.NORMAL)
                //setRevealWidth(20.dp2px())
                setIndicatorSliderColor(
                    ColorUtil.getResourceColor(context, com.songcha.library_common.R.color.banner_indictor_normal),
                    ColorUtil.getResourceColor(context, com.songcha.library_common.R.color.banner_indictor_selected))
                registerLifecycleObserver(lifecycle)

                setOnPageClickListener{v,p->
                    BookUriHandler.handle(viewModel.bannerList.value!![p].tarUrl)
                }
            }.create(list.toList())
            //databinding.taskBvp.refreshData(list)
        }

    }

    private fun initDailyTask(list:MutableList<DailyTaskBean.DataBean>){
        databinding.taskRcv.apply {
            layoutManager=LinearLayoutManager(context)
            mAdapter=DailyTaskAdapter(list)
            mAdapter!!.setOnItemChildClickListener(this@TaskFragment)
            adapter=mAdapter
        }
        //commit complete task,prevent not commit success before
        /*for (i in 0 until list.size){
            val item=list[i]
            if(item.isAccomplish) continue
            when(item.taskType){
                1->{
                    val readChapterCount=BookTodayReadChapterCountDaoManager.getTodayReadChapterCount()
                    if(readChapterCount>=item.norm)
                        viewModel.completeTask(i)
                }
                2->{
                    val readTime=BookTodayReadTimeDaoManager.getTodayReadTime()
                    if(readTime>=item.norm*60){
                        if(BuildConfig.DEBUG)
                            ToastUtil.show("完成阅读时间超60分钟任务")
                        viewModel.completeTask(i)
                    }

                }
                3->{
                    val commentWriteCount=BookTodayCommentWriteCountDaoManager.getTodayCommentWriteCount()
                    if(commentWriteCount>=item.norm)
                        viewModel.completeTask(i)
                }
                4->{
                    val watchRewardAdvertCount=BookTodayWatchRewardAdvertCountDaoManager.getTodayWatchAdvertCount()
                    if(watchRewardAdvertCount>=item.norm)
                        viewModel.completeTask(i)
                }

            }
        }*/

    }

    private fun initSignView(context: Context,list:MutableList<SignTaskBean.DataBean>,signDay:Int,llSign:LinearLayout){
        //val list= listOf("10","20","30","40","50","60","100")
        llSign.removeAllViews()
        for(i in list.indices){
            val item=list[i]
            val child=LinearLayout(context)
            child.orientation=LinearLayout.VERTICAL
            val tvCoin=TextView(context)
            tvCoin.text="+${item.awardGold}"
            tvCoin.textSize=14f
            tvCoin.setTextColor(ColorUtil.getResourceColor(context,R.color.signin_title))
            val tvCoinLp=LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
            tvCoin.layoutParams=tvCoinLp

            val viewGold=LayoutInflater.from(context).inflate(R.layout.task_item_sign_gold,child,false)
            val viewGoldLp=LinearLayout.LayoutParams(28.dp2px(),28.dp2px())
            viewGoldLp.topMargin=10.dp2px()
            viewGold.layoutParams=viewGoldLp

            val ccl=viewGold.findViewById<CustomContainerLayout>(R.id.task_ccl_sign)
            val iv=viewGold.findViewById<ImageView>(R.id.task_iv_sign)

            if(i<=signDay-1){
                iv.setImageResource(R.mipmap.task_icon_yes)
                ccl.setStartColor(ColorUtil.getResourceColor(context,R.color.signin_item_start))
                ccl.setEndColor(ColorUtil.getResourceColor(context,R.color.signin_item_end))
            }else{
                iv.setImageResource(R.mipmap.task_icon_gold)
                ccl.setStartColor(Color.TRANSPARENT)
                ccl.setEndColor(Color.TRANSPARENT)
            }

            val tvDay=TextView(context)
            tvDay.text="第${item.numberDays}天"
            val tvDayLp=LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
            tvDayLp.topMargin=10.dp2px()
            tvDay.layoutParams=tvDayLp
            tvDay.textSize=9f
            tvDay.setTextColor(Color.parseColor("#6C6A6A"))

            child.addView(tvCoin)
            child.addView(viewGold)
            child.addView(tvDay)

            child.gravity=Gravity.CENTER_HORIZONTAL

            val lp=LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.WRAP_CONTENT)
            lp.weight=1f
            lp.gravity=Gravity.CENTER_VERTICAL
            child.layoutParams=lp

            llSign.addView(child)

            child.setOnClickListener {
                if(!UserInfoManager.checkJumpLogin()) return@setOnClickListener
                if(signDay>=7) return@setOnClickListener
                //cannot sign go back
                if(i!=signDay){
                    return@setOnClickListener
                }
                if(UserInfoManager.isTodaySignIn()){
                    ToastUtil.show("今天已签到，请明天再来")
                    return@setOnClickListener
                }
                sign(i)
            }

        }
    }

    private fun sign(position:Int){
        //ToastUtil.show(i.toString())
        viewModel.sign(position)
    }


    /*private var mTTAdNative: TTAdNative?=null
    private var mTTRewardVideoAd: TTRewardVideoAd?=null
    private var mAdSlot:AdSlot?=null*/

   /* private fun initAdvert(){
        if(mTTAdNative==null){
            mTTAdNative = TTAdSdk.getAdManager().createAdNative(requireContext())
        }
        if(mAdSlot==null){
            mAdSlot = AdSlot.Builder()
                .setCodeId(resources.getString(R.string.advert_reward_id))
                .setAdLoadType(TTAdLoadType.LOAD)
                .build()
        }

        loadRewardAdvert(mAdSlot!!)
    }*/

   /* private fun loadRewardAdvert(adSlot: AdSlot){
        mTTAdNative!!.loadRewardVideoAd(adSlot,TTAdNativeRewardVideoAdListener(this))
    }*/

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        when(view.id){
            R.id.task_btn_goto->{
                if(viewModel.dailyTaskList.value==null) return
                val task=viewModel.dailyTaskList.value!![position]
                if(task.isAccomplish) return
                view as CustomButton
                if(view.text == "领金币"){
                    if(!UserInfoManager.checkJumpLogin()) return
                    when(task.taskType){
                        DailyTaskAdapter.TYPE_READ_CHAPTER->{
                            val readChapterCount=BookTodayReadChapterCountDaoManager.getTodayReadChapterCount()
                            if(readChapterCount>=task.norm)
                                viewModel.completeTask(position)
                        }
                        DailyTaskAdapter.TYPE_READ_TIME->{
                            val readTime=BookTodayReadTimeDaoManager.getTodayReadTime()
                            if(readTime>=task.norm*60)
                                viewModel.completeTask(position)
                        }
                        DailyTaskAdapter.TYPE_WRITE_COMMENT->{
                            val commentWriteCount=BookTodayCommentWriteCountDaoManager.getTodayCommentWriteCount()
                            if(commentWriteCount>=task.norm)
                                viewModel.completeTask(position)
                        }
                        DailyTaskAdapter.TYPE_WATCH_REWARD_ADVERT->{
                            val watchRewardAdvertCount=TodayWatchRewardAdvertCountDaoManager.getTodayWatchAdvertCount()
                            if(watchRewardAdvertCount>=task.norm)
                                viewModel.completeTask(position)
                        }

                    }

                }else if(view.text == "去完成"){
                    if(task.taskType==DailyTaskAdapter.TYPE_WATCH_REWARD_ADVERT){
                        if(UserInfoManager.checkJumpLogin()){
                            SystemConfigurationManager.getSystemConfiguration()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe({
                                    loadRewardAdvert()
                                },{

                                })
                        }
                    }else{
                        MainEventProxy.postToHomeEvent()
                    }
                }

            }
        }
    }

    private var mHadShowInsertScreenAdvert = false

    private fun showInsertScreenAdvert(){
        if(mHadShowInsertScreenAdvert) return

        AdvertCoverHelper.loadAdvertByCover(requireActivity(),AdvertHelper.ADVERT_TYPE_INSERT_SCREEN,VarConfig.ADVERT_TASK_INSERT_SCREEN_INFO,
            null,0f,object:AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    mHadShowInsertScreenAdvert = true
                }

                override fun onError(type: Int, code: Int, msg: String) {

                }

                override fun onClose(type: Int) {

                }
            })
    }

    override fun onBottomNavigationItemChange(position: Int,tag:String) {
        if(tag==TAG){
            //refresh gold
            UMengHelper.onUMEvent(requireContext(), "bottom_tab_task")
            showTaskInfo()
            showInsertScreenAdvert()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    override fun onLoginSuccessEvent(event: LoginSuccessEvent) {
        onGetData()
        viewModel.completeReaderRewardUnLoginTasks()
    }

    @Subscribe(sticky = true)
    fun onDailyTaskCompleteEvent(event: DailyTaskCompleteEvent) {
        viewModel.getDailyTask()
        EventBus.getDefault().removeStickyEvent(event)
    }

    @Subscribe
    fun onLogoutEvent(event:LogoutEvent){
        onGetData()
    }

    @Subscribe
    fun onUnRegisterEvent(event:LogoutEvent){
        onGetData()
    }

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.task_ll_gold_explain->{
                val db=CustomDialog.Companion.Builder(v.context)
                db.setDialogTitle("金币说明")
                    .setDialogMsg("金币可用于兑换免费看小说的时长，可用于兑换vip会员体验时间。\n金币可通过签到、完成每日任务获取，当使用金币兑换看小说时长/vip会员时，将会扣除对应金币数。")
                    .setCancelText("")
                    .create().show()
            }
            R.id.task_ll_sign_explain->{
                val db=CustomDialog.Companion.Builder(v.context)
                db.setDialogTitle("签到说明")
                    .setDialogMsg("签到可获得金币奖励，若连续签到则奖励更加丰厚。连续签到中途不能中断，若中断则下次签到将从第一天算起。")
                    .setCancelText("")
                    .create().show()
            }
        }
    }

    private fun loadRewardAdvert(){
        AdvertCoverHelper.loadAdvertByCover(requireActivity(),AdvertHelper.ADVERT_TYPE_REWARD,VarConfig.ADVERT_TASK_REWARD_INFO,
            null,0f,
            object:AdvertHelper.ILoadAdvertCommonListener{
                override fun onSuccess(type: Int, height: Int, view: View?) {
                    TodayWatchRewardAdvertCountDaoManager.addTodayWatchAdvertCount()
                }

                override fun onError(type: Int,code:Int,msg:String) {
                    ToastUtil.show("加载视频广告失败")
                }

                override fun onClose(type: Int) {

                }

            })

    }

}